<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visible"
    :title="dialogTitle"
    width="750px"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form ref="formRef" :model="form" label-width="100" :rules="rules">
      <el-row>
        <template v-for="(item, index) in formItem" :key="index">
          <el-col :span="item.span">
            <el-form-item
              v-if="!item.hidden"
              :label="item.label"
              :prop="item.prop"
            >
              <el-input
                v-if="['input', 'textarea'].includes(item.type)"
                v-model="form[item.prop]"
                :type="item.type"
                :placeholder="`请输入${item.label}`"
                :disabled="item.disabled"
                clearable
              />
              <el-select
                v-else-if="item.type === 'select'"
                v-model="form[item.prop]"
                :placeholder="`请选择${item.label}`"
                clearable
                :disabled="item.disabled"
                style="width: 100%"
              >
                <el-option
                  v-for="(option, optionIndex) in item.options.data"
                  :key="optionIndex"
                  :label="option[item.options.label]"
                  :value="option[item.options.value]"
                />
              </el-select>
              <el-radio-group
                v-else-if="item.type === 'radio'"
                v-model="form[item.prop]"
              >
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import useEvent from "@/utils/useEvent";
import request from "@/utils/request";

const { eventBusOn, eventBusEmit } = useEvent();
defineOptions({
  name: "EAMFAULTSYSTEMMANAGEADDORUPDATE",
  inheritAttrs: false,
});

const loading = ref(false);
const visible = ref(false);
const url = ref("");
const callback = ref("");
const dialogTitle = ref("");
const formRef = ref(ElForm);
const rules = ref({});
const formItem = ref([]);

const form = ref({});

const getInfo = async (id: string, path: string) => {
  const { data } = await request({
    url: `/eam/${path}/get/${id}`,
    method: "get",
  });
  return Promise.resolve(data);
};

onMounted(() => {
  eventBusOn(
    "addOrUpdate",
    async ({ obj: { formData, path, callbackEmit, title }, row }) => {
      dialogTitle.value = `新增${title}`;
      const info = ref();
      if (row !== undefined) {
        await getInfo(row.id, path).then((data) => {
          info.value = data;
        });
      }
      formItem.value = formData;
      url.value = path;
      callback.value = callbackEmit;
      form.value = baseCol.concat(formData).reduce((acc, item) => {
        acc[item.prop] = info.value ? info.value[item.prop] : item.default;
        return acc;
      }, {} as Record<string, any>);
      rules.value = formData.reduce((acc, item) => {
        acc[item.prop] = item.rules;
        return acc;
      }, {} as Record<string, any>);
      visible.value = true;
    }
  );
});

const closeDialog = () => {
  visible.value = false;
};
const handleSubmit = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = form.value.id ? "编辑" : "新增";
      await request({
        url: `/eam/${url.value}/save`,
        method: "post",
        data: form.value,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      eventBusEmit(callback.value);
    }
  });
};

const baseCol = [
  {
    prop: "id",
    hidden: true,
    default: "",
  },
  {
    prop: "version",
    hidden: true,
    default: "",
  },
  {
    prop: "createTime",
    hidden: true,
    default: "",
  },
  {
    prop: "createdUserId",
    hidden: true,
    default: "",
  },
  {
    prop: "lastUpdateTime",
    hidden: true,
    default: "",
  },
  {
    prop: "lastUpdatedUserId",
    hidden: true,
    default: "",
  },
];
</script>
